﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using MTRC.ODMS.BLL.COM;
using System.Xml;
using APJUtil = APJ.Util;
using System.IO;
using System.Data.SqlClient;
using MTRC.ODMS.BLL.SOM;

namespace MTRC.ODMS.Web.SOM.Popup
{
    public partial class UCSignatureNew : MTRC.ODMS.Web.UserControl.BaseUserControl
    {
        // add by dylan 20151015
        public bool IsPhotoCaptureEnabled
        {
            get { return this.btnPhotoCapture.Enabled; }
            set { this.btnPhotoCapture.Enabled = value; }
        }
        public bool IsHandWrittenEnabled
        {
            get { return this.btnHandWritten.Enabled; }
            set { this.btnHandWritten.Enabled = value; }
        }
      
        public void Page_Load(object sender, EventArgs e)
        {
            //add by gordon 20160215 ISU51
            DateTime start = DateTime.Now;
           // BLL.SOM.Log.Logger("UCSignatureNew->Page_Load ----Start", ODMUser.ID, ODMUser.UserGroupName);
            //add end by gordon 20160215 ISU51

            if (!IsPostBack) 
            {
                this.btnPhotoCapture.Text = this.GetLabel("SOM_SignType_PhotoCapture");
            }
            //Modify by elvis on 20180131 for SER-2018056 （default not load  SignaturePaint.）-->
            //SignaturePaint.Visible = false;
            //<--Modify by elvis on 20180131 for SER-2018056 （default not load  SignaturePaint.）
            if (hdnSignType.Value == "1")
            {
                SignaturePhoto.Style["display"] = "";
                SignaturePaint.Style["display"] = "none";
                SignaturePic.Style["display"] = "none";
            }
            else if (hdnSignType.Value == "1complete")/*Comment by jack 20151013 for u230*/
            {
                SignaturePhoto.Style["display"] = "none";
                SignaturePaint.Style["display"] = "";
                SignaturePic.Style["display"] = "none";
            }
            else
            {
                SignaturePaint.Style["display"] = "";
                SignaturePhoto.Style["display"] = "none";
                SignaturePic.Style["display"] = "none";
            }
           
            if (this.PreviousSignFullFileName != this.GetSignatureFullFileName(1))
            {
                this.IsNeedSignAgain = false;
            }

            //------------------------------20090121--------------
            string fullFileName = "";
            fullFileName = string.Concat(Session[MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival]);
           
            //modify by tim for Save Signature into database 20160225
            string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;

            if (fullFileName != string.Empty)
            {
                if (fullFileName.Equals("SOM_EventSignCheck"))
                {
                    PAlert(this.GetMessage("SOM_EventSignCheck"));
                    Session[MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival] = null;
                    Session[signatureName] = null;
                }
                else
                {
                    this.hdnSignFileName.Value = fullFileName;
                    //prefix: Signature_Handwritten_
                    //prefix: Signature_PhotoCapture_
                    if (fullFileName.IndexOf("Signature_Handwritten_") > -1)
                    {
                        this.hdnSignType.Value = "2";
                        //modify by tim 20160629 for check signature
                        using (SqlDataReader drStationEventSignReaderArrive = ODMS.BLL.SOM.Event.StationEventAdmReg.CheckSignature(this.StationEventID))
                        {
                            if (drStationEventSignReaderArrive.HasRows)
                            {

                                string SignatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;
                                string signatureNameDeparture = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Departure + "_" + ODMUserID;
                                Session[signatureNameDeparture] = Session[SignatureName];
                               
                            }
                        }
                    }
                    else
                    {
                        this.hdnSignType.Value = "1";
                    }
                    Session[MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival] = null; //set this value to empty//but this has a hidden issue, the better way is use return value from popup form, but ,it can not work now,
                    this.SetImgSignatureScript();
                }
            }
            //-------------end-----------------20090121--------------

            this.btnPhotoCapture.Enabled = false; //Add by jack 20160201 for ISU38 Disabled the btnPhotoCapture button

            this.SetFlagPictureShow();
            
            this.Page.RegisterStartupScript("UCS", string.Format("<script>var CONTROL_SignFileName = '{0}';</script>", this.hdnSignFileName.ClientID));

            //add by gordon 20160215 ISU51
            string Flag = string.Empty;
            DateTime end = DateTime.Now;
            if ((end - start).Seconds > 3)
            {
                Flag = "->[Slow:" + ((end - start).Seconds).ToString() + "s]";
            }
            //BLL.SOM.Log.Logger("UCSignatureNew->Page_Load"+Flag+" ----End", ODMUser.ID, ODMUser.UserGroupName);
            //add end by gordon 20160215 ISU51
        }

        /// <summary>
        /// Set control enable or disable
        /// </summary>
        /// <param name="enable">enable or disable</param>
        /// <param name="eventSignType">1. arrival, 2. departure, 2--only for AR use</param>
        public void SetEnable(bool enable, int eventSignType)
        {
            eventSignType = 1; //hard code: 1 means: arrival

            //this.btnPhotoCapture.Enabled = enable; //huangyao 20090122 fixed TD:1156
           // this.btnHandWritten.Enabled = enable; //huangyao 20090122 fixed TD:1156
            //can open view sign Picture, but can not sign
            //this.btnOpenCapture.Enabled = enable;
            //OpenSignatureForm(); return false;
            string isReadOnly = "true";
            if (enable)
            {
                isReadOnly = "false";
            }
            else
            {
                //if read only, no need signature again
                this.IsNeedSignAgain = false;
            }

            string scriptNeedToBind = "";

    
           // scriptNeedToBind = "OpenPhotoCaptureForm('" + isReadOnly + "', '" + eventSignType.ToString() + "', '" + "" + "', '" + this.ClientID + "'); return false;";
            //this.btnPhotoCapture.Attributes.Add("OnClick", "return ShowPhotoWritten();");

            //scriptNeedToBind = "OpenHandWrittenForm('" + isReadOnly + "', '" + eventSignType.ToString() + "', '" + "" + "', '" + this.ClientID + "'); return false;";
           // this.btnHandWritten.Attributes.Add("OnClick", "ShowHandWritten()");
  
        }

        //modify by tim for save signature into database 20160229
        public void clearSignSession()
        {
            string signatureNameArrival = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;
            string signatureNameDeparture = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Departure + "_" + ODMUserID;
            string signatureNameDepartureTemp = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_DepartureTemp + "_" + ODMUserID;
            string signatureNameTransferTemp = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_TransferTemp + "_" + ODMUserID;
            Session[signatureNameArrival] = null;
            Session[signatureNameDeparture] = null;
            Session[signatureNameDepartureTemp] = null;
            Session[signatureNameTransferTemp] = null;
            Session[MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival] = null;
        }


        //------20081013 night---
        /// <summary>
        /// Move temp signature picture file to real path
        /// </summary>
        public void SaveTempFileToRealPath()
        {
            //add by gordon 20160215 ISU51
            DateTime start = DateTime.Now;
            //BLL.SOM.Log.Logger("UCSignatureNew->SaveTempFileToRealPath ----Start", ODMUser.ID, ODMUser.UserGroupName);
            //add end by gordon 20160215 ISU51

            string fileName = this.GetSignatureFullFileName(1);
            string realPath = APJ.Util.Utility.GetAppSetting("SOM_SignatureFilePath");
            string tempPath = APJ.Util.Utility.GetAppSetting("SOM_SignatureFileTempPath");
            //remove to real path
            //SOM_SignatureFilePath
            //string fullFileName = APJ.Util.Utility.GetAppSetting("SOM_SignatureFileTempPath") + "Signature_PhotoCapture_" + Guid.NewGuid().ToString() + ".gif";
            if (fileName.IndexOf(realPath) == -1)
            {
                //if the signature full file name do not contains Real Path, it means it a temp signature picture
                fileName = APJUtil.Utility.ConvertFromBase64(fileName);
                //add by gordon 20160114 - change save sign file from full to relative U297
                if (tempPath.LastIndexOf("\\") != tempPath.Length - 1)
                    tempPath += "\\";

                fileName = tempPath + fileName;
                //add end by gordon 20160114
                if (File.Exists(fileName))
                {
                    //add by gordon 20160215 ISU51
                    DateTime feStart = DateTime.Now;
                    //BLL.SOM.Log.Logger("UCSignatureNew->SaveTempFileToRealPath->FileExistsAction ----Start", ODMUser.ID, ODMUser.UserGroupName);
                    //add end by gordon 20160215 ISU51

                    //add by gordon 20160114 - change save sign file from full to relative U297
                    if (realPath.LastIndexOf("\\") != realPath.Length - 1)
                        realPath += "\\";
                    //add end by gordon 20160114
                    string newFileName = "";
                    if (this.GetSignatureType() == 1)
                    {
                        newFileName = realPath + "Signature_PhotoCapture_" + Guid.NewGuid().ToString() + ".gif";
                    }
                    else
                    {
                        newFileName = realPath + "Signature_Handwritten_" + Guid.NewGuid().ToString() + ".gif";
                    }
                    //remove
                    File.Move(fileName, newFileName);
                    //this.PreviousSignFullFileName //must delete previous file
                    if (File.Exists(this.PreviousSignFullFileName))
                    {
                        File.Delete(this.PreviousSignFullFileName);
                    }
                    this.SetSignatureFullFileName(1, newFileName);

                    //add by gordon 20160215 ISU51
                    string feFlag = string.Empty;
                    DateTime feEnd = DateTime.Now;
                    if ((feEnd - feStart).Seconds > 3)
                    {
                        feFlag = "->[Slow:" + ((feEnd - feStart).Seconds).ToString() + "s]";
                    }
                    //BLL.SOM.Log.Logger("UCSignatureNew->SaveTempFileToRealPath->FileExistsAction" + feFlag + " ----End", ODMUser.ID, ODMUser.UserGroupName);
                    //add end by gordon 20160215 ISU51
                }
                else
                {
                    throw new Exception("Can not find the signature file, you should signature again!");
                }

            }

            //add by gordon 20160215 ISU51
            string Flag = string.Empty;
            DateTime end = DateTime.Now;
            if ((end - start).Seconds > 3)
            {
                Flag = "->[Slow:" + ((end - start).Seconds).ToString() + "s]";
            }

            //BLL.SOM.Log.Logger("UCSignatureNew->SaveTempFileToRealPath" + Flag + " ----End", ODMUser.ID, ODMUser.UserGroupName);
            //add end by gordon 20160215 ISU51
        }

        /// <summary>
        /// Set user control internal language
        /// </summary>
        public void SetLanguage()
        {
            //this.lblSignature.Text = this.GetLabel("SOM_Signature_LabelText", true);
            //this.btnPhotoCapture.Text = this.GetLabel("SOM_SignType_PhotoCapture"); //huangyao 20090122 fixed TD:1156
            //this.btnHandWritten.Text = this.GetLabel("SOM_SignType_HandWritten"); //huangyao 20090122 fixed TD:1156
            //this.btnOpenCapture.ToolTip = this.GetLabel("SOM_SignType_OpenCaptureToolTip");
        }

        private void SetFlagPictureShow()
        {
           
            //modify by tim for save signature to database
            //string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;
            //if (Session[signatureName] == null)
            if (string.Concat(this.hdnSignFileName.Value) == string.Empty) //huangyao 20090122 fixed TD:1156
            {
                this.imgSignature.ImageUrl = "~/Images/SOM/Sign_UnSignature.gif";
            }
            else
            {
                this.imgSignature.ImageUrl = "~/Images/SOM/Sign_Signature.gif";
            }
            //should get from resource.xml
            //this.btnOpenCapture.ToolTip = "Show Book On Signature details panel";
        }

        /// <summary>
        /// get signature full file name
        /// </summary>
        /// <param name="eventSignType">1. arrival, 2. departure, 2--only for AR use</param>
        /// <returns></returns>
        public string GetSignatureFullFileName(int eventSignType)
        {
            eventSignType = 1; //hard code

            string fullFileName = "";
            if (eventSignType == 1)
            {
                fullFileName = this.hdnSignFileName.Value; //huangyao 20090122 fixed TD:1156
                fullFileName = fullFileName.Substring(fullFileName.LastIndexOf("\\") + 1);//add by gordon 20160114 - change save file path from full to relative
            }
            else
            {

            }

            return fullFileName;
        }

        protected void hdnForRefresh_ServerChange(object sender, EventArgs e)
        {
            string ss = "";
        }


        /// <summary>
        /// Set some user control internal value
        /// </summary>
        /// <param name="eventSignType">1.AL, FL, AR Event Time, 2. Only for AR depart time</param>
        /// <param name="signType">1--photo capture, 2. handwritting</param>
        /// <param name="signFileName">when had signed , pass signature file name, else empty</param>
        public void InitUCSignatureValue(int eventSignType, int signType, string signFileName)
        {
            this.hdnSignType.Value = signType.ToString(); //huangyao 20090122 fixed TD:1156

            eventSignType = 1; //hard code

            this.SetSignatureFullFileName(eventSignType, signFileName);
            this.PreviousSignFullFileName = signFileName;

            this.SetImgSignatureScript(); //huangyao 20090122 fixed TD:1156
        }

        /// <summary>
        /// judge need signature again
        /// Just use in AL currently
        /// </summary>
        public bool IsNeedSignAgain
        {
            get
            {
                bool isNeedSignAgain = false;
                bool.TryParse(string.Concat(ViewState[MTRC.ODMS.BLL.COM.Session.SOM_IsNeedSignAgain]), out isNeedSignAgain);
                return isNeedSignAgain;
            }
            set
            {
                ViewState[MTRC.ODMS.BLL.COM.Session.SOM_IsNeedSignAgain] = value;
            }
        }

       //add by tim 20160701
        public byte[] SignatureTemp
        {
            get
            {
              byte[] Sign =  (byte[])ViewState["SignatureTemp"];
              return Sign;
            }
            set
            {
                this.ViewState["SignatureTemp"] = value;
            }
        }

        public int StationEventID
        {
            get
            {
                if (this.ViewState["StationEventID"] != null)
                {
                    int stationID = int.Parse(this.ViewState["StationEventID"].ToString());
                    return stationID > 0 ? stationID : -1;
                }
                else
                {
                    return -1;
                }
               
            }
            set
            {
                this.ViewState["StationEventID"] = value;
            }
        }


        public string confirm
        {
            get {return "con"; }
            set { confirm = value; }

        }

        private string PreviousSignFullFileName
        {
            get
            {
                return string.Concat(this.ViewState["_previousSignFullFileName"]);
            }
            set
            {
                this.ViewState["_previousSignFullFileName"] = value;
            }
        }

        private void SetSignatureFullFileName(int eventSignType, string signatureFullFileName)
        {
            eventSignType = 1; //hard code

            if (eventSignType == 1)
            {
                this.hdnSignFileName.Value = signatureFullFileName; //huangyao 20090122 fixed TD:1156
                //add by benson 2015-09-11 begin
                if (string.IsNullOrEmpty(signatureFullFileName))
                {
                    imgSignature.ImageUrl = "~/Images/SOM/Sign_UnSignature.gif";
                }
                //add by benson 2015-09-11 end
            }
            else
            {

            }
        }

        /// <summary>
        /// Retrieve signature type
        /// 1. means Photo capture
        /// 2. means Signature painting
        /// </summary>
        /// <returns></returns>
        public int GetSignatureType()
        {
            //int signatureType = 1;
            //if (RadioPhoto.Checked == true)
            //{
            //    signatureType = 1;
            //}
            //else
            //{
            //    signatureType = 2;
            //}
            ////int.TryParse(hdnSignType.Value.Trim(), out signatureType); //huangyao 20090122 fixed TD:1156

            //return signatureType;

            int signatureType = 1;
            
            
            int.TryParse(hdnSignType.Value.Trim(), out signatureType); 

            return signatureType;
        }

        private void SetImgSignatureScript()
        {
            //add by gordon 20160215 ISU51
            DateTime start = DateTime.Now;
           // BLL.SOM.Log.Logger("UCSignatureNew->SetImgSignatureScript ----Start", ODMUser.ID, ODMUser.UserGroupName);
            //add end by gordon 20160215 ISU51

            //add by tim 20160701
            string signatureName = MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Arrival + "_" + ODMUserID;
            SignatureTemp = (byte[])Session[signatureName];
            //end add
            string scriptNeedToBind = "";
            string fullFileName = string.Concat(this.hdnSignFileName.Value).Trim();
            //if (Session[signatureName] != null)
            if (fullFileName != string.Empty)
            {
                //add by gordon 20160114 - change save sign file from full to relative U297
                string realPath = APJ.Util.Utility.GetAppSetting("SOM_SignatureFilePath");
                string tempPath = APJ.Util.Utility.GetAppSetting("SOM_SignatureFileTempPath");

                if (fullFileName.IndexOf(realPath) == -1 && fullFileName.IndexOf(tempPath) == -1)
                {
                    if (realPath.LastIndexOf("\\") != realPath.Length - 1)
                        realPath += "\\";

                    fullFileName = realPath + fullFileName;
                }
                //add end by gordon 20160114

                this.ReportDownloadPath = fullFileName;
                //modify by tim 20160406 for save signature into database
               // this.ViewState["GetPicURL"] = "~/SOM/Popup/GetPic.aspx?abc=" + Guid.NewGuid().ToString();
                this.ViewState["GetPicURL"] = "~/SOM/Popup/GetPicNew.aspx?abc=" + "SignatureArrival";
                this.imgSignaturePic.ImageUrl = this.ViewState["GetPicURL"].ToString();

                fullFileName = HttpUtility.UrlEncode(fullFileName);
                

                if (this.GetSignatureType() == 1)
                {
                    //photo
                    //scriptNeedToBind = "OpenPhotoCaptureForm('" + "true" + "', '" + 1.ToString() + "', '" + fullFileName + "', '" + this.ClientID + "'); return false;";
                    //this.imgSignature.Attributes.Add("OnClick", scriptNeedToBind);
                    //update by gordon 20150813
                    //this.imgSignature.Attributes.Add("OnClick", "OpenSignatureForm()");
                    fullFileName = HttpUtility.HtmlEncode(fullFileName.Replace("\\", "\\\\"));
                    this.imgSignature.Attributes.Add("OnClick", "OpenHandWrittenForm('true','2','"+fullFileName+"')");
                    //--------------
                   // this.btnPhotoCapture.Attributes.Add("OnClick", "ShowPhotoWritten()");
                }
                else
                {
                   // hand
                  //  scriptNeedToBind = "OpenHandWrittenForm()";


                    //update by gordon 20150813
                    //this.imgSignature.Attributes.Add("OnClick", "OpenSignatureForm()");
                    fullFileName = HttpUtility.HtmlEncode(fullFileName.Replace("\\", "\\\\"));
                    this.imgSignature.Attributes.Add("OnClick", "OpenHandWrittenForm('true','2','" + fullFileName + "')");
                    //--------------
                    //this.btnHandWritten.Attributes.Add("OnClick", "ShowHandWritten()");
                }
                this.imgSignature.Attributes.Add("style", "cursor:hand;");
                this.imgSignature.ToolTip = this.GetLabel("SOM_SignViewPreviousPic");

                //----------------------
                string findString = "Bottom";
                string controlName = "";
                string controlValue = "";
                //controlName = this.ClientID + @"$hdnSignFileName";
                //controlValue = ( (System.Web.UI.HtmlControls.HtmlInputHidden) this.Parent.FindControl(controlName) ).Value;
                if (this.ClientID.IndexOf(findString) > -1)
                {
                    //set oppsite control value
                    //controlName = this.ClientID.Substring(this.ClientID.IndexOf(findString) ) + @"$hdnSignFileName"; 
                    controlName = this.ClientID.Substring(0, this.ClientID.IndexOf(findString));
                }
                else
                {
                    //controlName = this.ClientID + findString + @"$hdnSignFileName"; 
                    controlName = this.ClientID + findString;
                }
                //((System.Web.UI.HtmlControls.HtmlInputHidden)this.Parent.FindControl(controlName)).Value = controlValue;
                object oppsiteControl = this.Parent.FindControl(controlName);
                //if (oppsiteControl != null)
                //{
                //    UCSignature tempUCSignature = (UCSignature)this.Parent.FindControl(controlName);
                //    if (tempUCSignature.GetSignatureFullFileName(1) != this.hdnSignFileName.Value)
                //    {
                //        tempUCSignature.InitUCSignatureValue(1, this.GetSignatureType(), this.hdnSignFileName.Value);
                //        //tempUCSignature.SetEnable(this.btnPhotoCapture.Enabled, 1);
                //        tempUCSignature.IsNeedSignAgain = this.IsNeedSignAgain;
                //    }
                //}
                //---------end
            }
            else
            {
                this.imgSignature.Attributes.Add("style", "cursor:default;disable");
                this.imgSignature.Attributes.Add("OnClick", ""); //clear the Event
                this.imgSignature.ToolTip = "";
            }

            //add by gordon 20160215 ISU51
            string flag = string.Empty;
            DateTime end = DateTime.Now;
            if ((end - start).Seconds > 3)
            {
                flag = "->[Slow:" + ((end - start).Seconds).ToString() + "s]";
            }

            //BLL.SOM.Log.Logger("UCSignatureNew->SetImgSignatureScript" + flag + " ----End", ODMUser.ID, ODMUser.UserGroupName);
            //add end by gordon 20160215 ISU51
        }
        //Modify by elvis on 20180131 for SER-2018056 （default not load  SignaturePaint.）-->
        protected void btnHandWritten_Click(object sender, EventArgs e)
        {
            SignaturePaint.Visible = true;
        }
        //<--Modify by elvis on 20180131 for SER-2018056 （default not load  SignaturePaint.）
      

        //protected void btnPhotoCapture_Click(object sender, EventArgs e)
        //{
        //    hdnSignType.Value = "1";
        //    Page_Load(null, null);
        //}

        //protected void btnHandWritten_Click(object sender, EventArgs e)
        //{
        //    hdnSignType.Value = "2";
        //    Page_Load(null,null);
        //}

       

        
    }
}